import React, { Suspense } from 'react';
import { formatMessage } from 'umi-plugin-react/locale';
import PageLoading from '@/components/PageLoading';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { Button, Card, Col, Row, Table, Modal, message, Tag, Pagination, Input } from 'antd';
import { connect } from 'dva';
import { postSysRoleDisabled } from "@/services/user";
import moment from 'moment';
import UserSession from '@/UserSession';

const { confirm } = Modal;

class AuthList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      search: '',
      total: 0,
      page: 1,
      limit: 10,
      loading: true,
      dataSource: []
    }
  }

  componentDidMount() {
    this.getList()
  }

  getList = () => {
    const { page, limit, search } = this.state
    const { dispatch } = this.props;
    this.setState({ loading: true }, () => {
      dispatch({
        type: 'authManage/getRoleLists',
        payload: { current: page, size: limit, search },
        callback: res => {
          // console.log(res);
          this.setState({ loading: false, dataSource: res.records, total: res.total })
        },
      });
    })
  }

  queryByPage = (page, size) => {
    this.setState({ page, limit: size }, () => this.getList());
  }

  openAddModal = row => {
    const { history } = this.props;
    const currentUser = UserSession.getCurrentUser()
    history.push({
      pathname: currentUser.tenantId == '1' ? "/defaultData/authManage/authEdit" : "/authManage/authEdit",
      query: row ? { authId: row.id } : {},
    });
  }

  authorizationData = row => {
    const { history } = this.props;
    const currentUser = UserSession.getCurrentUser()
    history.push({
      pathname: currentUser.tenantId == '1' ? '/defaultData/authManage/authorization' : "/authManage/authorization",
      query: { authId: row.id },
    });
  }

  removeData = row => {
    const that = this;
    confirm({
      title: formatMessage({ id: 'account.authManage.authList.confirmDelete', defaultMessage: '确定要删除吗?' }),
      okText: formatMessage({ id: 'common.ok', defaultMessage: '确定' }),
      okType: 'danger',
      cancelText: formatMessage({ id: 'common.cancel', defaultMessage: '取消' }),
      onOk() {
        const { dispatch } = that.props;
        dispatch({
          type: 'authManage/removeList',
          payload: { id: row.id },
          callback: res => {
            message.info(res.msg);
            that.setState({ page: 1 }, () => that.getList());
          },
        });
      },
      onCancel() { },
    });
  }

  onDisabledClick = async (checked, id) => {
    let res = await postSysRoleDisabled({ id, disabled: !checked });
    console.log(res);
    if (res.code === 0) {
      message.success("操作成功");
      this.getList()
    }
  }

  onValuePage = value => {
    this.setState({ search: value })
  }

  render() {
    const { currentUser } = this.props;
    const { total, page, loading, dataSource, search } = this.state;
    const columns = [
      {
        title: formatMessage({ id: 'account.authManage.authList.roleName', defaultMessage: '角色名称' }),
        dataIndex: 'roleName',
        key: 'roleName',
        width: 300
      },
      {
        title: formatMessage({ id: 'account.authManage.authList.updateTime', defaultMessage: '更新时间' }),
        dataIndex: 'createTime',
        key: 'createTime',
        width: 300,
        render: (createTime) => {
          if (createTime) {
            return moment(createTime).format('YYYY-MM-DD hh:mm:ss')
          } else {
            return createTime;
          }
        }
      },
      {
        title: formatMessage({ id: 'account.authManage.authList.permissionCenter', defaultMessage: '权限中心' }),
        dataIndex: 'menuNameList',
        key: 'menuNameList',
        render: text => {
          return (
            <span style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>
              {text && text.length > 0 && text.map(row => (
                <Tag color="#F3F3F3" style={{ color: '#000', padding: '4px 12px' }}>{row}</Tag>
              ))}
            </span>
          );
        }
      },
      {
        title: formatMessage({ id: 'account.authManage.authList.operation', defaultMessage: '操作' }),
        width: 200,
        fixed: "right",
        render: (text, record, index) => {
          return (
            <span style={{ display: 'flex', gap: '16px' }}>
              <span style={{ color: '#3E5BFF', cursor: 'pointer' }} onClick={() => this.openAddModal(record)}>{formatMessage({ id: 'account.authManage.authList.edit', defaultMessage: '编辑' })}</span>
              {currentUser.tenantId == '1' && record.roleType != 0 ? (
                <span
                  style={{ color: record.disabled ? '#3E5BFF' : '#faad14', cursor: 'pointer' }}
                  onClick={() => this.onDisabledClick(record.disabled, record.id)}
                >
                  {record.disabled ? formatMessage({ id: 'account.authManage.authList.enable', defaultMessage: '启用' }) : formatMessage({ id: 'account.authManage.authList.disable', defaultMessage: '停用' })}
                </span>
              ) : (
                <span style={{ color: '#3E5BFF', cursor: 'pointer' }} onClick={() => this.authorizationData(record)}>{formatMessage({ id: 'account.authManage.authList.authorize', defaultMessage: '授权' })}</span>
              )}
              {record.roleType == 0 ? null : (
                <span style={{ color: '#D54941', cursor: 'pointer' }} onClick={() => this.removeData(record)}>{formatMessage({ id: 'account.authManage.authList.delete', defaultMessage: '删除' })}</span>
              )}
            </span>
          )
        }
      },
    ];

    return (
      <Suspense fallback={<PageLoading />}>
        <PageHeaderWrapper>
          <Card bordered={false} style={{ height: '100%' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
                <Input value={search} placeholder={formatMessage({ id: 'account.authManage.authList.searchPlaceholder', defaultMessage: '输入角色名称' })} onChange={e => this.onValuePage(e.target.value)} />
                <Button type="primary" onClick={this.getList}>{formatMessage({ id: 'account.authManage.authList.search', defaultMessage: '查询' })}</Button>
              </div>
              <Button type="primary" onClick={() => this.openAddModal()} icon='plus'>{formatMessage({ id: 'account.authManage.authList.addRole', defaultMessage: '新增角色' })}</Button>
            </div>
            <Row style={{ margin: '20px 0 0' }}>
              <Col span={24}>
                <Table
                  loading={loading}
                  dataSource={dataSource}
                  columns={columns}
                  rowKey={'id'}
                  pagination={false}
                  scroll={{ x: "auto" }}
                />
                <Pagination
                  total={total}
                  current={page}
                  onChange={this.queryByPage}
                  showQuickJumper={true}
                  style={{ marginTop: 20, textAlign: 'right' }}
                />
              </Col>
            </Row>
          </Card>
        </PageHeaderWrapper>
      </Suspense>
    )
  }
}


export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(AuthList);
